package com.youhome.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chen365 on 2017/7/14.
 */
public class ValidationUtils {
    /**
     * 判断Email格式是否正确
     *
     * @param email 邮箱
     * @return
     */
    public static boolean isEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 判断是否是手机号
     *
     * @param mobile
     * @return
     */
    public static boolean isPhone(String mobile) {
        // "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        String regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


    /**
     * 一个简单的签名认证，规则：
     * 1. 将请求参数按ascii码排序
     * 2. 拼接为a=value&b=value...这样的字符串（不包含sign）
     * 3. 混合密钥（secret）进行md5获得签名，与请求的签名进行比较
     */
    public static boolean validateSign(HttpServletRequest request) {
        //String public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBLVL9k3wiKzPbinLeyJ0koUFod8J2fJebv3gy2n29yzkys27FqhdmsUncmQlzPNaE1z1kN/k6IGgYUyLs8gV7JQPVVkXia1DyM1ffo82BmnQux4BJ4uf21ujQcJwNkOTc43XMeDpejDp4MnDXxwpLEY4u4xGC2nDm9r/X8sB9SwIDAQAB";
        //String public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlfB8WygSZXX5WQjMwtx1wnaRtk4eBEJDaJ60b4VviVYq1qsrMFFMyKpkKJpBi7Yc1qt9lxAXXJsgfINFnunZ37YYipLQ9wokcQszR83DoRFzSsYmgdA98smdjNFFljlK+x8SfuQi3Ac8bDfVOIng/rNWyguSNiBzAU1v2w16fWQIDAQAB";
        String public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCSZ0LyiNZB5zGLAT+3w/ImwT1BN7/WUT4ogGLTwIcpP63kXJh1Gig3ufJnz+AsIDjBp5ACdF8eFmyvfhsQfi7m7YOUo6e8muTs56wcd/u885ddJJNHpy7I6pD8ayceEvjfm9BjtshNpyGrGmfwUnH1dHvc9Owo8Ld4DmbtOECfMQIDAQAB";
//        String publicKeyString = public_key.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");
//        System.err.println(publicKeyString);

        try {
            String sign = request.getParameter("sign");//获得请求签名，如sign=19e907700db7ad91318424a97c54ed57
            System.err.println("sign:" + sign);
            if (StringUtils.isEmpty(sign)) {
                return false;
            }
            List<String> keys = new ArrayList<>(request.getParameterMap().keySet());
            System.err.println("keys:" + keys);
            keys.remove("sign");//排除sign参数
            Collections.sort(keys);//排序

            StringBuilder sb = new StringBuilder();
            for (String key : keys) {
                sb.append(key).append("=").append(request.getParameter(key)).append("&");//拼接字符串
            }
            String linkString = sb.toString();
            linkString = StringUtils.substring(linkString, 0, linkString.length() - 1);//去除最后一个'&'
            System.err.println("link:" + linkString);
            //System.err.println("rsa_public_key:"+rsa_public_key);
            String password = "c303701a92932475b516e5033b7a3e0b";
            //return RSAUtils.verify(linkString.getBytes(), rsa_public_key, sign);
            //return RSAUtils.verify(linkString.getBytes(), publicKeyString, sign);
            //return RSAUtils2.verify(linkString.getBytes(), public_key, sign.replace(" ","+"));
            //String key = "you37^9ld.kf43k@#1";
            return DigestUtils.md5Hex(linkString + password).equals(sign);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return false;
    }

    public static String generateSign(Map<String,Object> maps) {
        List<String> keys = new ArrayList<>(maps.keySet());
        Collections.sort(keys);//排序
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append("=").append(maps.get(key)).append("&");//拼接字符串
        }
        String linkString = sb.toString();
        linkString = StringUtils.substring(linkString, 0, linkString.length() - 1);//去除最后一个'&'
        System.err.println("link:" + linkString);
        //System.err.println("rsa_public_key:"+rsa_public_key);
        String password = "c303701a92932475b516e5033b7a3e0b";

        return DigestUtils.md5Hex(linkString + password);


    }
    /*
    public static void main(String[] args) {
        boolean mobile = isPhone("13401086966");
        System.err.println(mobile);
    }

    */

}
